package cn.idietrade.idietradeusermodule8004.utils;

import cn.idietrade.common.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class EmailUtil {
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Resource
    private RedisUtil redisUtil;


    //简单邮箱发送
    public boolean sendEmail(String subject,String text,String from,String to){
        boolean flag = true;
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            simpleMailMessage.setSubject(subject);
            simpleMailMessage.setText(text);
            simpleMailMessage.setFrom(from);
            simpleMailMessage.setTo(to);
            javaMailSender.send(simpleMailMessage);
        }catch (Exception e){
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    //复杂邮箱发送
    public boolean sendEmailPlus(String setTo){
        boolean flag = true;
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //组装
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setSubject("欢迎注册二手交易网");
            Integer code = MD5.getRandomCode();
            mimeMessageHelper.setText("<p style='color:red'>验证码："+code+"</p>",true);
            mimeMessageHelper.setFrom("g508324563@163.com");
            mimeMessageHelper.setTo(setTo);
            //将验证码保存到redis 保存5分钟
            redisUtil.setStr(setTo,code.toString(),5l);
            javaMailSender.send(mimeMessage);
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }


    //校验邮箱验证是否正确
    public boolean checkEmailCode(String email,String code){
        boolean flag = false;
        String str = redisUtil.getStr(email);
        if(code.equals(str)){
            flag=true;
        }
        return flag;
    }
}
